<template>
  <div>
    <a @click="showModal">{{ text }}</a>
    <a-modal 
      :title="title + ' - ' + row.roleName"
      centered
      :maskClosable="false"
      :width="800"
      v-model="visible"
      :okText="$t('modal_submit')"
      :cancelText="$t('modal_cancel')"
      @ok="handleOk"
      :okButtonProps="okButtonProps"
    >
      <a-tree
        checkable
        @expand="onExpand"
        :expandedKeys="expandedKeys"
        :autoExpandParent="autoExpandParent"
        @check="onCheck"
        v-model="checkedKeys"
        :treeData="treeData"
      >
        <template slot="titleI18n" slot-scope="{title}">
          {{ $t(title) }}
        </template>
      </a-tree>
    </a-modal>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  props: {
    text: { type: [String] },
    title: { type: [String] },
    row: { type: [Object], default: () => { return {} } },
  },
  data() {
    return {
      visible: false,
      okButtonProps: {},
      autoExpandParent: true,
      expandedKeys: [],
      checkedKeys: [],
      treeData: [],
    }
  },
  methods: {
    showModal() {
      this.treeData = []
      this.checkedKeys = []
      this.expandedKeys = []
      this.fetch()
      this.visible = true
      this.okButtonProps = {}
    },
    onExpand(expandedKeys) {
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    fetch() {
      axios({
        method: 'get',
        url: '/infra/role/getPendingResource',
        params: {
          roleId: this.row.id,
        },
      }).then((res) => {
        let nodes = res.data.treeData
        this.applyScopedSlots(nodes)
        this.treeData = nodes
        this.checkedKeys = res.data.checkedKeys
        this.expandedKeys = res.data.expandedKeys
      })
    },
    applyScopedSlots(nodes) {
      nodes.forEach((item) => {
        if (item.children) {
          this.applyScopedSlots(item.children)
        }
        item.scopedSlots = {title: "titleI18n"}
      });
    },
    handleOk() {
      this.okButtonProps ={ props: {disabled: true} }
      // submit

      axios({
        method: 'post',
        url: '/infra/role/auth',
        data: {
          roleId: this.row.id,
          funcIds: this.checkedKeys
        },
      }).then(() => {
        this.visible = false
        this.$success({
          title: this.$t('success_message'),
          content: this.$t('submit_success'),
          okText: this.$t('modal_ok'),
        });
      }).catch(() => {
        this.okButtonProps = {}
      });
      
    },
  }
}
</script>
